package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import com.example.cardgame.model.CardMatchingGame

class ThirdActivity : AppCompatActivity(), View.OnClickListener {
    lateinit var game: CardMatchingGame
    private val cardButtons = mutableListOf<Button>()

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_third) // 确保布局文件为activity_third.xml

        // 处理系统栏边距
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 初始化卡片网格
        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
        for (v in gridLayout.children) {
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        // 重置游戏按钮
        findViewById<Button>(R.id.button_reset).setOnClickListener {
            game.resetGame()
            updateUI()
        }

        // 返回按钮（点击返回分数）
        findViewById<Button>(R.id.button_back).setOnClickListener {
            val resultIntent = Intent()
            resultIntent.putExtra("currentScore", game.score) // 传递当前分数
            setResult(RESULT_OK, resultIntent)
            finish() // 关闭当前页面返回上一级
        }
    }

    // 更新UI显示（卡片状态和分数）
    private fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.ic_launcher_background)
            }
        }
        // 更新分数显示
        val scoreText = findViewById<TextView>(R.id.textView)
        scoreText.text = String.format("%s%d", getString(R.string.score), game.score)
    }

    // 卡片点击事件
    override fun onClick(v: View?) {
        if (v is Button && v.id != R.id.button_reset && v.id != R.id.button_back) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
}